package com.liuwei.spring.cloud.biz.support;

import com.liuwei.spring.cloud.framework.spring.ApplicationHelper;
import io.micrometer.tracing.TraceContext;
import io.micrometer.tracing.Tracer;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : TraceHelper
 * @version V1.0
 * @date: 2024/1/5 4:55 PM
 * @Description: TODO
 */
public class TraceHelper {

    public static class Micrometer{
        public static boolean putBaggage(String key,String value){
            Tracer tracer = ApplicationHelper.getBean(Tracer.class);
            if(ObjectUtils.isNotEmpty(tracer)){
                //String traceId = tracer.currentTraceContext().context().traceId();
                TraceContext traceContext = tracer.currentTraceContext().context();
                Map<String,String> baggage = tracer.getAllBaggage();
                baggage.put(key,value);
                //tracer.createBaggageInScope(key,value);
                return true;
            }
            return false;
        }

        public static Map<String,String> getBaggage(){
            Tracer tracer = ApplicationHelper.getBean(Tracer.class);
            if(ObjectUtils.isNotEmpty(tracer)){
                //String traceId = tracer.currentTraceContext().context().traceId();
                TraceContext traceContext = tracer.currentTraceContext().context();
                Map<String,String> baggage = tracer.getAllBaggage();
                return baggage;
            }
            return new HashMap<>();
        }

        public static String traceId(){
            Tracer tracer = ApplicationHelper.getBean(Tracer.class);
            if(ObjectUtils.isNotEmpty(tracer)
                    && ObjectUtils.isNotEmpty(tracer.currentTraceContext())
                    && ObjectUtils.isNotEmpty(tracer.currentTraceContext().context())){
                return tracer.currentTraceContext().context().traceId();
            }
            return StringUtils.EMPTY;
        }
    }


}
